"""
任务消费者
"""


from alibabacloud_imageseg20191230.client import Client
from alibabacloud_imageseg20191230.models import SegmentCommonImageRequest
from alibabacloud_tea_openapi.models import Config
from alibabacloud_tea_util.models import RuntimeOptions




import  time ,os , requests ,string ,random 
from loguru import logger
import mysql.connector 


#禁用requests出现的取消ssl验证的警告
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)


# 任务状态数据
TASK_STATUS  = {
    "QUEUE":1,  #排队中
    "DOING":2,  #执行中
    "DONE":3,   #已完成
    "CANCEL":4  #已取消
}
"""
获取当前年月日时分秒
"""
def getNow():
    now = time.strftime( '%Y-%m-%d %H:%M:%S', time.localtime() )
    return now


# 本地测试
# def newConn():

#     return mysql.connector.connect(
#         user='root', 
#         password='rootroot',  
#       host='127.0.0.1',  
#       database='huanyi',
#       autocommit=True,
#       buffered=True  #防止使用fetchonede时候结果集中还有数据没有取出，出现unread result的报错信息
#       )

# 远程正式
def newConn():
    return mysql.connector.connect(
        user='huanyiroot', 
        password='rootroot',  
      host='127.0.0.1',  
      database='huanyi',
      autocommit=True,
      buffered=True  #防止使用fetchonede时候结果集中还有数据没有取出，出现unread result的报错信息
      )



def Log(content):
    ymd = time.strftime( '%Y-%m-%d', time.localtime() )
    name = f"log-{ymd}.txt"

    curDir = "./log/"
    file_name=os.path.join( curDir , name ) 
    if not  os.path.exists(curDir) :
        os.mkdir(curDir)

    with open(file_name , 'a' , encoding='utf-8') as  f:
        now = time.strftime( '%Y-%m-%d %H:%M:%S', time.localtime() )
        f.write(f"[{now}]:{content}")
        f.write('\n')
    



# 通用分割
def segment(image_url):

    config = Config(
        # 创建AccessKey ID和AccessKey Secret，请参考https://help.aliyun.com/document_detail/175144.html。
        # 如果您用的是RAM用户的AccessKey，还需要为RAM用户授予权限AliyunVIAPIFullAccess，请参考https://help.aliyun.com/document_detail/145025.html。
        # 从环境变量读取配置的AccessKey ID和AccessKey Secret。运行代码示例前必须先配置环境变量。
        access_key_id="LTAI5tG9qooU44jid4HNsz1n",
        access_key_secret="sY2JkTFqf9NhVpu6LPw1CLUyvsPkKJ",
        # 访问的域名。
        endpoint='imageseg.cn-shanghai.aliyuncs.com',
        # 访问的域名对应的region
        region_id='cn-shanghai'
    )
    segment_common_image_request = SegmentCommonImageRequest(
       image_url=image_url,
       return_form='crop'
       # ReturnForm参数设置：
       # 指定返回的图像形式。
       # 如果设置为mask，则返回单通道黑白图。
       # 如果设置为crop，则返回裁剪之后的四通道PNG图（裁掉边缘空白区域）。
       # 如果设置为whiteBK，则返回白底图。
       # 如果不设置或者设置为其他值，则返回四通道PNG图。
    )
    runtime = RuntimeOptions()
    try:
      # 初始化Client
      client = Client(config)
      response = client.segment_common_image_with_options(segment_common_image_request, runtime)
      # 获取整体结果
      # logger.info(response.body.data.image_url)
      return response.body.data.image_url
      # {'Data': {'ImageURL': 'http://vibktprfx-prod-prod-damo-eas-cn-shanghai.oss-cn-shanghai.aliyuncs.com/seg-common-image/2024-12-05/85eb9acc-ff08-4999-ae5f-37d61364781a/image.png?Expires=1733426113&OSSAccessKeyId=LTAI4FoLmvQ9urWXgSRpDvh1&Signature=tc5t5%2FNXif2ksG7Qy8ueihLLOvU%3D'}, 'RequestId': '06476383-8572-5D1B-ABC7-35D43B383901'}


    except Exception as error:
      # 获取整体报错信息
      logger.info(error)
      # 获取单个字段
      logger.info(error.code)
      # tips: 可通过error.__dict__查看属性名称
      return False





# 开始任务
def startKouTuTask( s , id , source_oss_image ):

    conn = newConn()
    cursor = conn.cursor( dictionary=True ) 


    logger.info(f"source_oss_image{source_oss_image}")
    res = segment( source_oss_image )
    if res ==False:
        logger.error(f'任务:{id},抠图失败')
        # 更新任务为已取消
        cursor.execute( 'update koutu_task set status = %s where id=%s' , ( TASK_STATUS['CANCEL'] ,  id) )
    else:
        # 更新任务为已完成
        cursor.execute( 'update koutu_task set status = %s , segment_oss_image=%s  where id=%s' , ( TASK_STATUS['DONE'] ,res,  id) )

    cursor.close()
    conn.close()


if __name__ == "__main__":
    
    s = requests.Session()
    conn = newConn()
    cursor = conn.cursor( dictionary=True ) 

    while True:
        
        time.sleep(1)

        # 首先查找有没有排队中的任务
        cursor.execute( 'select id , source_oss_image from koutu_task  where status=%s limit 1' , (TASK_STATUS['QUEUE'],) )
        res = cursor.fetchone()
        # logger.info(res)
        if res == None:
            logger.info("没有排队中的任务")
            time.sleep(0.5)
            continue

        else:
            logger.info(f"找到排队中的任务,任务id：{res['id']}" )
            id=res['id']
            source_oss_image=res['source_oss_image']
            # 找到排队中的任务,更新为进行中
            cursor.execute( 'update koutu_task set status =%s where id=%s and status = %s' , (TASK_STATUS['DOING'] , id , TASK_STATUS['QUEUE'] ) )
            logger.info(f"更新任务{res['id']}为排队中" )
            # 开始执行任务
            # https://huanyi.oss-cn-shanghai.aliyuncs.com/1732883802556_TOVtRJgD.png
            logger.info(f"source_oss_image:{source_oss_image}")  
            startKouTuTask( s ,id , f"https://huanyi.oss-cn-shanghai.aliyuncs.com/{source_oss_image}")
           
